
<?php
/**
 * @file
 * Contains the theme's functions to manipulate Drupal's default markup.
 *
 * Complete documentation for this file is available online.
 * @see https://drupal.org/node/1728096
 */


/**
 * Override or insert variables into the maintenance page template.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("maintenance_page" in this case.)
 */
/* -- Delete this line if you want to use this function
function redflaggroup_preprocess_maintenance_page(&$variables, $hook) {
  // When a variable is manipulated or added in preprocess_html or
  // preprocess_page, that same work is probably needed for the maintenance page
  // as well, so we can just re-use those functions to do that work here.
  redflaggroup_preprocess_html($variables, $hook);
  redflaggroup_preprocess_page($variables, $hook);
}
// */

/**
 * Override or insert variables into the html templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("html" in this case.)
 */
/* -- Delete this line if you want to use this function
function redflaggroup_preprocess_html(&$variables, $hook) {
  $variables['sample_variable'] = t('Lorem ipsum.');

  // The body tag's classes are controlled by the $classes_array variable. To
  // remove a class from $classes_array, use array_diff().
  //$variables['classes_array'] = array_diff($variables['classes_array'], array('class-to-remove'));
}
// */

/**
 * Override or insert variables into the page templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("page" in this case.)
 */
/* -- Delete this line if you want to use this function
function redflaggroup_preprocess_page(&$variables, $hook) {
  $variables['sample_variable'] = t('Lorem ipsum.');
}
// */

/**
 * Override or insert variables into the node templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("node" in this case.)
 */
/* -- Delete this line if you want to use this function
function redflaggroup_preprocess_node(&$variables, $hook) {
  $variables['sample_variable'] = t('Lorem ipsum.');

  // Optionally, run node-type-specific preprocess functions, like
  // redflaggroup_preprocess_node_page() or redflaggroup_preprocess_node_story().
  $function = __FUNCTION__ . '_' . $variables['node']->type;
  if (function_exists($function)) {
    $function($variables, $hook);
  }
}
// */

/**
 * Override or insert variables into the comment templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("comment" in this case.)
 */
/* -- Delete this line if you want to use this function
function redflaggroup_preprocess_comment(&$variables, $hook) {
  $variables['sample_variable'] = t('Lorem ipsum.');
}
// */

/**
 * Override or insert variables into the region templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("region" in this case.)
 */
/* -- Delete this line if you want to use this function
function redflaggroup_preprocess_region(&$variables, $hook) {
  // Don't use Zen's region--sidebar.tpl.php template for sidebars.
  //if (strpos($variables['region'], 'sidebar_') === 0) {
  //  $variables['theme_hook_suggestions'] = array_diff($variables['theme_hook_suggestions'], array('region__sidebar'));
  //}
}
// */

/**
 * Override or insert variables into the block templates.
 *
 * @param $variables
 *   An array of variables to pass to the theme template.
 * @param $hook
 *   The name of the template being rendered ("block" in this case.)
 */
/* -- Delete this line if you want to use this function
function redflaggroup_preprocess_block(&$variables, $hook) {
  // Add a count to all the blocks in the region.
  // $variables['classes_array'][] = 'count-' . $variables['block_id'];

  // By default, Zen will use the block--no-wrapper.tpl.php for the main
  // content. This optional bit of code undoes that:
  //if ($variables['block_html_id'] == 'block-system-main') {
  //  $variables['theme_hook_suggestions'] = array_diff($variables['theme_hook_suggestions'], array('block__no_wrapper'));
  //}
}
// */

// yg20180601---begin
function xenyo_theme() {
  $items = array();
  // create custom user-login.tpl.php
  $items['user_login'] = array(
   'render element' => 'form',
   'path' => drupal_get_path('theme', 'xenyo') . '/templates',
   'template' => 'user-login',
   'preprocess functions' => array('xenyo_preprocess_user_login'
  ),
 );
 return $items;
}
// yg20180601---end


function xenyo_preprocess_page(&$variables) {
  if(arg(0) == "taxonomy" && arg(1) == "term") {
    $variables['page']['content']['system_main']['nodes'] = null;
  }

  $status = drupal_get_http_header("status");
  if ($status === '404 Not Found'){
    $variables['classes_array'][] = 'page404';
  }

  if (isset($variables['node'])) {
    if ($variables['node']->type == 'jtv') {
      $variables['theme_hook_suggestion'] = 'page__node__jtv';
    }
    else {
      $variables['theme_hook_suggestion'] = 'page__'. $variables['node']->type;
    }
  }
  else {
    foreach($variables['theme_hook_suggestions'] as $k => $v) {
      if ($v == 'page__gallery') {
        unset($variables['theme_hook_suggestions'][$k]);
      }
    }
  }
}

function xenyo_preprocess_block(&$variables) {
	if (function_exists('_gfp_is_block_managed'))
	{
		//dsm($variables['block_html_id']);
		$block_name = $variables['block_html_id'];
		$block_name = str_replace('block-block-', '', $block_name);
		$block_name = trim($block_name);
		$all_managed_blocks = _gfp_get_all_managed_blocks(TRUE);

		if (isset($all_managed_blocks[$block_name]))
		{
			//dsm($block_name);
			//$variables['content'] = "TEST";

			$block_info = $all_managed_blocks[$block_name];
			//dsm($block_info);

			$args = array();
			$slot = _gfp_custom_page_ads_slot($block_info['default_slot_name'], $block_name);
			$args['slot_name'] = $slot;
			$args['variable_salt'] = md5(time() . rand(0, 999));

			if (count($block_info) > 0)
			{
				$i = 1;

				foreach ($block_info['sizes'] as $size)
				{
					$args['slot_div_id_' . ($i - 1)] = 'div-gpt-ad-1455369085556-' . ($i - 1) . md5(time() . rand());

					$first_width = $size['ad_width'];
					$first_height = $size['ad_height'];

					if (is_array($size['ad_width']) && is_array($size['ad_height']))
					{
						$first_width = $size['ad_width'][0];
						$first_height = $size['ad_height'][0];
					}

					if ($size['slot_name_override'] != "")
					{
						$args['temp_slot' . $i] = $size['slot_name_override'];
					}
					else
					{
						$temp = $slot;
						_gfp_custom_replace_token($temp_slot, array("size" => $first_width . 'x' . $first_height));
						$args['temp_slot' . $i] = $temp;
					}

					$i++;
				}

				$args['block_identifier'] = md5('block_' . $block_name . '_' . time() . "_" . rand(0,999));

				_gfp_custom_replace_token($variables['content'], $args);
			}
		}
	}

  if($variables['block_html_id'] == 'block-menu-menu-jtv-menu') {

    if(($key = array_search('first', $variables['classes_array'])) !== false) {
      unset($variables['classes_array'][$key]);
    }
  }
}

function xenyo_status_messages($variables) {
	$display = $variables['display'];
	$output = '';

	$status_heading = array(
		'status' => t('Status message'),
		'error' => t('Error message'),
		'warning' => t('Warning message'),
	);
	foreach (drupal_get_messages($display) as $type => $messages) {
		$output .= "<div class=\"messages $type\">\n<div class=\"wrapper\">";
		if (!empty($status_heading[$type])) {
			$output .= '<h2 class="element-invisible">' . $status_heading[$type] . "</h2>\n";
		}
		if (count($messages) > 1) {
			$output .= " <ul>\n";
			foreach ($messages as $message) {
				$output .= '  <li>' . $message . "</li>\n";
			}
			$output .= " </ul>\n";
		}
		else {
			$output .= $messages[0];
		}
		$output .= "</div>\n</div>";
	}
	return $output;
}

function xenyo_breadcrumb($variables) {
  $breadcrumb = $variables['breadcrumb'];

  $crumbs = '<div class="breadcrumb">';
  if (!empty($breadcrumb)) {
    $crumbs .= '<span class="lflabel">' . context_get('hn_sw', 'bd_prefix') . '</span>';
    $crumbs .= '<ul class="breadcrumbs">';
    $count = count($breadcrumb);
    for($i=0; $i < $count; $i++) {
      $crumbs .= '<li>' . $breadcrumb[$i];
      if ($i != $count - 1) {
        //$crumbs .= ' > ';
      }
      $crumbs .= '</li>';
    }
    $crumbs .= '</ul>';
  }
  $crumbs .= '</div>';
  return $crumbs;
}

function xenyo_form_element($variables) {
  $element = &$variables['element'];

  // This function is invoked as theme wrapper, but the rendered form element
  // may not necessarily have been processed by form_builder().
  $element += array(
    '#title_display' => 'before',
  );

  // Add element #id for #type 'item'.
  if (isset($element ['#markup']) && !empty($element ['#id'])) {
    $attributes ['id'] = $element ['#id'];
  }
  // Add element's #type and #name as class to aid with JS/CSS selectors.
  $attributes ['class'] = array('form-item');
  if (!empty($element ['#type'])) {
    $attributes ['class'][] = 'form-type-' . strtr($element ['#type'], '_', '-');
  }
  if (!empty($element ['#name'])) {
    $attributes ['class'][] = 'form-item-' . strtr($element ['#name'], array(' ' => '-', '_' => '-', '[' => '-', ']' => ''));
  }
  // Add a class for disabled elements to facilitate cross-browser styling.
  if (!empty($element ['#attributes']['disabled'])) {
    $attributes ['class'][] = 'form-disabled';
  }
  $output = '<div' . drupal_attributes($attributes) . '>' . "\n";

  // If #title is not set, we don't display any label or required marker.
  if (!isset($element['#title'])) {
    $element ['#title_display'] = 'none';
  }
  $prefix = isset($element ['#field_prefix']) ? '<span class="field-prefix">' . $element ['#field_prefix'] . '</span> ' : '';
  $suffix = isset($element ['#field_suffix']) ? ' <span class="field-suffix">' . $element ['#field_suffix'] . '</span>' : '';



  switch ($element['#title_display']) {
    case 'before':
    case 'invisible':
      $output .= ' ' . theme('form_element_label', $variables);
      $output .= ' ' . $prefix . $element ['#children'] . $suffix . "\n";
      break;

    case 'after':
      $output .= ' ' . $prefix . $element ['#children'] . $suffix;
      $output .= ' ' . theme('form_element_label', $variables) . "\n";
      break;

    case 'none':
    case 'attribute':
      // Output no label and no required marker, only the children.
      $output .= ' ' . $prefix . $element ['#children'] . $suffix . "\n";
      break;
  }

  if (!empty($element['#description'])) {
    $output .= '<div class="description">' . $element ['#description'] . "</div>\n";
  }

  $output .= "</div>\n";

  return $output;
}






/*
Calendar header alter
*/

function xenyo_date_nav_title($params) {
    $granularity = $params['granularity'];
    $view = $params['view'];
    $date_info = $view->date_info;
    $link = !empty($params['link']) ? $params['link'] : FALSE;
    $format = !empty($params['format']) ? $params['format'] : NULL;
    switch ($granularity) {
//        case 'year':
//            $title = $date_info->year;
//            $date_arg = $date_info->year;
//            break;
        case 'month':
            $format = !empty($format) ? $format : (empty($date_info->mini) ? 'F Y' : 'F Y');
            $title = date_format_date($date_info->min_date, 'custom', $format);
            $date_arg = $date_info->year .'-'. date_pad($date_info->month);
            break;
//        case 'day':
//            $format = !empty($format) ? $format : (empty($date_info->mini) ? 'l, F j Y' : 'l, F j');
//            $title = date_format_date($date_info->min_date, 'custom', $format);
//            $date_arg = $date_info->year .'-'. date_pad($date_info->month) .'-'. date_pad($date_info->day);
//            break;
//        case 'week':
//            $format = !empty($format) ? $format : (empty($date_info->mini) ? 'F j Y' : 'F j');
//            $title = t('Week of @date', array('@date' => date_format_date($date_info->min_date, 'custom', $format)));
//            $date_arg = $date_info->year .'-W'. date_pad($date_info->week);
//            break;
    }
    if (!empty($date_info->mini) || $link) {
    // Month navigation titles are used as links in the mini view.
    $attributes = array('title' => t('View full page month'));
    $url = date_pager_url($view, $granularity, $date_arg, TRUE);
    return l($title, $url, array('attributes' => $attributes));
    }
    else {
    return $title;
    }
}


function xenyo_form_alter(&$form, &$form_state, $form_id)
{
  global $user;

  if ($form_id == 'comment_form')
  {
     $form['actions']['submit']['#value'] = t('Post comment');

    $form['comment_body']['und'][0]['value']['#attributes'] = array(
      'placeholder' => t('Write a new comment')
    );
  }

  if ($form_id == 'comment_node_risk_talk_form')
  {
    //unset($form['author']['_author']);
    $user_obj = user_load($user->uid);
    $user_rendered = user_view($user_obj, 'teaser');
    $user_pic_uri = "public://user-default.png";

    if (isset($user_obj->picture->uri))
    {
      $user_pic_uri = $user_obj->picture->uri;
    }

    $image_url = image_style_url('80x80', $user_pic_uri);

    $form['author']['_author']['#prefix'] = '<div class="author_wrapper">';
    $form['author']['_author']['#prefix'] .= '<div class="user-profile">';
    $form['author']['_author']['#prefix'] .= '<div class="user-picture">';
    $form['author']['_author']['#prefix'] .= '<a href="' . url('user/' . $user->uid) . '">' . sprintf('<img src="%s">', $image_url) . '</a>';
    $form['author']['_author']['#prefix'] .= '</div>';
    $form['author']['_author']['#prefix'] .= '</div>';
    $form['author']['_author']['#suffix'] = '</div>';

    $form['comment_body']['und'][0]['value']['#attributes'] = array(
      'placeholder' => t('Write a new comment')
    );
  }

  if ($form_id == 'comment_form' && $form['#entity']->node_type == 'comment_node_risk_talk')
  {
    $form['#submit'][] = 'xenyo_comment_node_risk_talk_form_submit';
  }
}

function xenyo_css_alter(&$css) {

  $status = drupal_get_http_header("status");
  if ($status === '404 Not Found'){
    return;
  }
    // unset global css files for jtv section
    // as jtv uses another design
    $arg0 = arg(0);
    if($arg0 == 'taxonomy') {
      $pages = "jessica-tv\n" . PHP_EOL . "jtv\n" . PHP_EOL . "jessica-channel\n" . PHP_EOL . "jessica-channel/*\n" . PHP_EOL . "jessica-tv/*\n" . PHP_EOL . "jtv/*\n";
    }
    else {
      $pages = "jessica-tv\n" . PHP_EOL . "jtv\n" . PHP_EOL . "jessica-channel\n" . PHP_EOL . "jessica-channel/*\n";
    }
    $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
    $page_match = drupal_match_path($path, $pages);
    if ($path != $_GET['q']) {
      $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
    }

    $n = menu_get_object();
    $page_match2 = false;
    if (!empty($n) && $n->type === 'jtv') {
        $page_match2 = true;
    }

    if ($page_match || $page_match2) {
        unset($css[path_to_theme() . '/css/styles.css']);
        unset($css[path_to_theme() . '/css/pages.css']);
        unset($css[path_to_theme() . '/css/lotfy/lotfy.css']);
        unset($css[path_to_theme() . '/css/j-code.css']);
        unset($css[path_to_theme() . '/css/pages-less.css']);
    }
}


function xenyo_js_alter(&$js) {
  $status = drupal_get_http_header("status");
  if ($status === '404 Not Found'){
    return;
  }
    // unset global css files for jtv section
    // as jtv uses another design
    $pages = "jessica-tv\n" . PHP_EOL . "jtv\n" . PHP_EOL . "jessica-channel\n" . PHP_EOL . "jessica-channel/*\n";
    $path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
    $page_match = drupal_match_path($path, $pages);
    if ($path != $_GET['q']) {
      $page_match = $page_match || drupal_match_path($_GET['q'], $pages);
    }

    $n = menu_get_object();
    $page_match2 = false;
    if (!empty($n) && $n->type === 'jtv') {
        $page_match2 = true;
    }

    if ($page_match || $page_match2) {
        unset($js[path_to_theme() . '/js/script.js']);
    }
}
//function xenyo_theme(&$existing, $type, $theme, $path) { 
//  $hooks['user_login'] = array(
//    'template' => 'templates/user/user_login',
//    'render element' => 'form', );                     // $hooks['user_register_form'] = array( // 'template' => 'templates/user/user_register', // 'render element' => 'form', // );
//  return $hooks; }